package com.transaction.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.transaction.common.util.JsonUtil;
import eu.bitwalker.useragentutils.UserAgent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Component
public class RequestZuulFilter extends ZuulFilter {

    private static Logger LOGGER = LoggerFactory.getLogger(RequestZuulFilter.class);

    /**
     * 网关类型
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 网关优先级
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 是否开启
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 过滤逻辑
     */
    @Override
    public Object run() throws ZuulException {

        LocalDateTime currentTime = LocalDateTime.now();

        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        //获取客户端操作系统
        String os = userAgent.getOperatingSystem().getName();
        //获取客户端浏览器
        String browser = userAgent.getBrowser().getName();
        //获得ip
        String ip = request.getHeader("Host");
        //請求地址
        String url = request.getRequestURL().toString();
        //請求頭
        String token = request.getHeader("Authorization");
        //请求参数
        String params = JsonUtil.getJson(request.getParameterMap());

        LOGGER.info("客户当前时间：{}，使用的操作系统：{}，使用的浏览器：{}，操作的电脑ip:{}," +
                        "\r\n请求的地址：{}，" +
                        "\r\n携带的token：{}," +
                        "\r\n请求参数：{}"
                ,currentTime,os,browser,ip,url,token,params);
        LOGGER.info("这是一个：test arthasHotSwap");

        return null;
    }
}
